package service.impl;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import dao.ExcelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.ExcelService;


import java.io.InputStream;

import java.util.List;
import java.util.Map;


@Service("/excelService")
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    ExcelMapper excelMapper;

    /**
     * 读取Excel文件并上传到数据库
     * @param inputStream 文件输入流
     * @return 是否上传成功
     * @throws Exception 插入数据出现问题时抛出异常
     */
    @Override
    public boolean inputExcel(InputStream inputStream) throws Exception{
            System.out.println("到达service");
            long start = System.currentTimeMillis();
            // 通过hutool工具操作excel文件
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            // 获取到excel表1 pmjlb
            System.out.println("读取sheet0");
            ExcelReader pmjlbRander = reader.setSheet(0);
            List<Map<String, Object>> pmjlbMaps = pmjlbRander.readAll();
            System.out.println("清空表sheet0");
            excelMapper.emptyTable("sheet0");//清空表
            System.out.println("开始插入数据到sheet0");
            for (Map<String, Object> map : pmjlbMaps) {
                excelMapper.insertData(map, "sheet0");
            }

            // 获取excel表2 ypjlb
            ExcelReader ypjlbReader = reader.setSheet(1);
            System.out.println("读取sheet1");
            List<Map<String, Object>> ypjlbMaps = ypjlbReader.readAll();
            System.out.println("清空表sheet1");
            excelMapper.emptyTable("sheet1");//清空表
            System.out.println("开始插入数据到sheet1");
            for (Map<String, Object> map : ypjlbMaps) {
                excelMapper.insertData(map, "sheet1");
            }
            long end = System.currentTimeMillis();
            System.out.println("处理完成，用时" + (end - start)/1000 + "秒");

            return true;
    }


}
